﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using EMPPLib;
using System.IO;
using System.Threading;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Text;

namespace SmsWebService
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class SmsWebService : System.Web.Services.WebService
    {
        [WebMethod(Description = "Send message")]
        public string SendSMS(SmsMessage smsMessage)
        {
            try
            {
                SMS sms = new SMS(smsMessage);
                sms.Run();
                smsMessage.Status = true;
                return (new DBUtil()).CreateSms(smsMessage);
            }
            catch (Exception ex)
            {
                smsMessage.Status = false;
                (new DBUtil()).CreateSms(smsMessage);
                LogUtil.WriteLog(ex.Message.ToString());
                return "Failed";
            }
        }

        [WebMethod(Description = "Get SMS Log")]
        public List<SmsMessage> GetSmsLog(QueryObject query)
        {
            return (new DBUtil()).GetSmsLogs(query);
        }
    }

    [Serializable]
    public class QueryObject
    {
        public string PhoneNumber { get; set; }
        public string OrderNumber { get; set; }
        public string BeginTime { get; set; }
        public string EndTime { get; set; }
        public string SmsContent { get; set; }
    }

    [Serializable]
    public class SmsMessage
    {
        public string SmsId { get; set; }
        public Guid CreatedBy { get; set; }
        public string OrderNumber { get; set; }
        public List<string> PhoneNumbers { get; set; }
        public string SmsContent { get; set; }
        public bool Status { get; set; }
    }

    public class DBUtil
    {
        private SqlParameter[] Parms;
        private SqlConnection Conn;

        public DBUtil()
        {
            Conn = new SqlConnection(SqlHelper.mainConnString);
        }

        public List<SmsMessage> GetSmsLogs(QueryObject query)
        {
            List<SmsMessage> logs = new List<SmsMessage>();
            
            StringBuilder strSql = new StringBuilder();

            strSql.Append("SELECT * FROM SmsLog WHERE 1=1 ");
            if (!string.IsNullOrEmpty(query.OrderNumber))
            {
                strSql.Append(" and OrderNumber like '%" + query.OrderNumber + "%'");
            }

            if (!string.IsNullOrEmpty(query.PhoneNumber))
            {
                strSql.Append(" and PhoneNumbers like '%" + query.PhoneNumber + "%'");
            }

            if (!string.IsNullOrEmpty(query.SmsContent))
            {
                strSql.Append(" and SmsContent like '%" + query.SmsContent + "%'");
            }

            SqlDataReader rd = SqlHelper.ExecuteReader(SqlHelper.mainConnString, CommandType.Text, strSql.ToString());
            while(rd.Read())
            {
                SmsMessage msg = new SmsMessage();
                msg.PhoneNumbers = new List<string>();
                msg.SmsId = rd["SmsId"].ToString();
                msg.SmsContent = rd["SmsContent"].ToString();
                var phones = rd["PhoneNumbers"].ToString().Split(',');

                foreach (var p in phones)
                {
                    if (!string.IsNullOrEmpty(p))
                    {
                        msg.PhoneNumbers.Add(p);
                    }
                }
                msg.OrderNumber = rd["OrderNumber"].ToString();
                msg.CreatedBy = new Guid(rd["CreatedBy"].ToString());
                msg.Status = Convert.ToBoolean(rd["Status"].ToString());
                logs.Add(msg);
            }

            return logs;
        }

        #region 信息添加
        /// <summary>
        /// 产品信息添加
        /// </summary>
        /// <param name="_productObj"></param>
        /// <returns></returns>
        public string CreateSms(SmsMessage smsObj)
        {
            Parms = new SqlParameter[] {					
					
                    new SqlParameter("@OrderNumber", SqlDbType.NVarChar,128),
					new SqlParameter("@PhoneNumbers", SqlDbType.NVarChar,512),
					new SqlParameter("@SmsContent", SqlDbType.NVarChar,256),
					new SqlParameter("@Status", SqlDbType.Bit),	
                    new SqlParameter("@CreatedBy", SqlDbType.UniqueIdentifier),
                    new SqlParameter("@SmsId",SqlDbType.UniqueIdentifier,16,"Output"),
                    new SqlParameter("@ReturnValue", SqlDbType.Int)
            };
            Parms[0].Value = smsObj.OrderNumber;

            string phones = string.Empty;
            foreach (string phoneNumber in smsObj.PhoneNumbers)
            {
                phones += phoneNumber + ",";
            }

            Parms[1].Value = phones;
            Parms[2].Value = smsObj.SmsContent;
            Parms[3].Value = smsObj.Status;
            Parms[4].Value = smsObj.CreatedBy;
            Parms[5].Direction = ParameterDirection.Output;
            Parms[6].Direction = ParameterDirection.ReturnValue;

            string result = string.Empty;
            int status = 0;
            try
            {
                SqlHelper.ExecuteNonQuery(Conn, CommandType.StoredProcedure, "SmsLog_Create", Parms);
                status = ((Parms[6].Value != null) ? ((int)Parms[6].Value) : -1);
                if (status == 0)
                {
                    result = "succeeded|" + smsObj.SmsId;
                }
                else
                {
                    result = status.ToString();
                }
            }
            catch (Exception err)
            {
                result = err.Message;
            }
            finally
            {
                Conn.Close();
                Conn.Dispose();
            }

            return result;
        }
        #endregion
    }

    public class SMS
    {
        private string host = ConfigurationManager.AppSettings["Host"].ToString();
        private int port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);
        private string accountId = ConfigurationManager.AppSettings["AccountId"].ToString();
        private string serviceId = ConfigurationManager.AppSettings["ServiceId"].ToString();
        private string password = ConfigurationManager.AppSettings["Password"].ToString();

        private string smsContent = string.Empty;
        private List<string> phoneNumbers = null;

        private EMPPLib.emptcl empp = new EMPPLib.emptclClass();

        public SMS(SmsMessage smsObj)
        {
            smsContent = smsObj.SmsContent;
            phoneNumbers = smsObj.PhoneNumbers;
        }

        private void CreateProcess(EMPPLib.emptcl empp)
        {
            empp.EMPPClosed += (new _IemptclEvents_EMPPClosedEventHandler(EMPPClosed));
            empp.EMPPConnected += (new _IemptclEvents_EMPPConnectedEventHandler(EMPPConnected));
            empp.MessageReceivedInterface += (new _IemptclEvents_MessageReceivedInterfaceEventHandler(MessageReceivedInterface));
            empp.SocketClosed += (new _IemptclEvents_SocketClosedEventHandler(SocketClosed));
            empp.StatusReceivedInterface += (new _IemptclEvents_StatusReceivedInterfaceEventHandler(StatusReceivedInterface));
            empp.SubmitRespInterface += (new _IemptclEvents_SubmitRespInterfaceEventHandler(SubmitRespInterface));
        }

        public void Run()
        {
            CreateProcess(this.empp);
            EMPPLib.ConnectResultEnum result = ConnectResultEnum.CONNECT_OTHER_ERROR;
            try
            {
                LogUtil.WriteLog("INDE 我们首次建立连接开始");
                result = this.empp.connect(host, port, accountId, password);
            }
            catch (Exception ex)
            {
                LogUtil.WriteLog("INDE 我们首次建立连接开始，以失败告终");
                LogUtil.WriteLog(ex.ToString());
            }


            int connectCounter = 0;
            while (result != EMPPLib.ConnectResultEnum.CONNECT_OK && result != EMPPLib.ConnectResultEnum.CONNECT_KICKLAST)
            {
                LogUtil.WriteLog("我们首次连接失败，接下来进行while重连----------" + connectCounter);
                connectCounter++;

                try
                {
                    result = this.empp.connect(host, port, accountId, password);
                }
                catch (Exception ex)
                {
                    LogUtil.WriteLog(ex.ToString());
                }

            }

            //if (this.smsContent.Length > 60)
            //{
            //    this.smsContent = this.smsContent.Substring(0, 60);
            //}

            for (int i = 0; i < 1; i++)
            {
                EMPPLib.ShortMessage shortMsg = new EMPPLib.ShortMessageClass();
                shortMsg.srcID = accountId;
                shortMsg.ServiceID = serviceId;
                shortMsg.needStatus = true;
                EMPPLib.Mobiles mobiles = new EMPPLib.MobilesClass();
                foreach (string phoneNumber in this.phoneNumbers)
                {
                    mobiles.Add(phoneNumber);
                }

                shortMsg.DestMobiles = mobiles;
                //shortMsg.content ="lujia  " + i + "  lujia    " +  msg + ":" + "【时间" + DateTime.Now.ToString() + "】";
                //shortMsg.SequenceID = new Random().Next(100000);
                shortMsg.content = this.smsContent;
                LogUtil.WriteLog("我们打印原始的短信内容：" + this.smsContent);
                shortMsg.SendNow = true;
                empp.needStatus = true;
                if (empp != null && empp.connected == true)
                {
                    LogUtil.WriteLog("\r\n");
                    LogUtil.WriteLog("目前的连接状况是：" + empp.connected);
                    LogUtil.WriteLog("目前的短信的seqid是：" + shortMsg.SequenceID);
                    LogUtil.WriteLog("the empp.sequceid:" + empp.SequenceID);
                    LogUtil.WriteLog("IF语句   我们即将发送短信：" + shortMsg.content);
                    empp.submit(shortMsg);
                    LogUtil.WriteLog("IF语句   我们已经发送短信：" + shortMsg.content);
                    Thread.Sleep(200);
                }
                else
                {
                    LogUtil.WriteLog("连接已经关闭，我们即将重新连接：现在我们在else语句里面");
                    Reconnect();
                    LogUtil.WriteLog("\r\n");
                    LogUtil.WriteLog("目前的连接状况是：" + empp.connected);
                    LogUtil.WriteLog("目前的shortmsgseqid是：" + shortMsg.SequenceID);
                    LogUtil.WriteLog("目前的emppseqid是：" + empp.SequenceID);

                    LogUtil.WriteLog("ELSE语句   我们即将发送短信：" + this.smsContent);
                    empp.submit(shortMsg);
                    LogUtil.WriteLog("ELSE语句   我们已经发送短信：" + this.smsContent);
                    Thread.Sleep(200);
                }
            }

            Thread.Sleep(100);
        }

        private void SubmitRespInterface(SubmitResp sm)
        {
            string str = "submitResp: msgId=" + sm.MsgID + ", seqId=" + sm.SequenceID + ", result=" + sm.Result;
            LogUtil.WriteLog("我们收到提交返回：" + str);
        }

        private void EMPPClosed(int errorCode)
        {
            LogUtil.WriteLog("发生了EMPPClose事件了");
        }

        private void SocketClosed(int errorCode)
        {
            string str = "SocketClosed:errorCode=" + errorCode + ",connected=" + empp.connected;
            LogUtil.WriteLog("我们现在发生了socketclose事件：" + "errorcoded is :" + errorCode + "我们即将进行重新连接");
            Reconnect();
        }

        private void Reconnect()
        {
            this.empp = new EMPPLib.emptclClass();
            this.CreateProcess(this.empp);
            LogUtil.WriteLog("Reconnect 发生异常，我们正在重新连接");
            EMPPLib.ConnectResultEnum result = ConnectResultEnum.CONNECT_OTHER_ERROR;

            try
            {
                result = this.empp.connect(host, port, accountId, password);
            }
            catch (Exception ex)
            {
                LogUtil.WriteLog(ex.ToString());
            }

            while (result != EMPPLib.ConnectResultEnum.CONNECT_OK && result != EMPPLib.ConnectResultEnum.CONNECT_KICKLAST)
            {
                LogUtil.WriteLog("Reconnect WHILE 发生异常，我们进行重新连接");

                try
                {
                    result = this.empp.connect(host, port, accountId, password);
                    Thread.Sleep(500);
                }
                catch (Exception ex)
                {
                    Thread.Sleep(500);
                    LogUtil.WriteLog(ex.ToString());

                }
            }

            LogUtil.WriteLog("congratulation , now the connection is ok or kicklast");
            Thread.Sleep(500);
        }


        private void MessageReceivedInterface(SMDeliverd sm)
        {
            string str = "收到手机回复:srcId=" + sm.srcID + " ,content=" + sm.content + "企业扩展位" + sm.DestID;
            string content = sm.content.Trim();
            LogUtil.WriteLog(str);
            LogUtil.WriteLog(content + "我们到此结束");
        }

        private void StatusReceivedInterface(StatusReport sm)
        {
            string str = "收到状态报告: seqId=" + sm.SeqID + ", msgId=" + sm.MsgID + ", mobile=" + sm.DestID + ", destId=" + sm.SrcTerminalId + ", status=" + sm.Status;
            LogUtil.WriteLog(str);

        }

        private void EMPPConnected()
        {
            LogUtil.WriteLog("已连接");
        }
    }

    public class LogUtil
    {

        public static void WriteLog(string log)
        {

            string path = ConfigurationManager.AppSettings["smsLogDirectory"].ToString();

            StreamWriter streamWriter;

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string monthDirectory = DateTime.Now.ToString("yyyy-MM");
            path = path + "\\" + monthDirectory;

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string fileName = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd")+".txt";

            if (!File.Exists(fileName))
            {
                streamWriter = File.CreateText(fileName);
                streamWriter.Close();
            }

            using (FileStream fileStream = new FileStream(fileName, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Write))
            {
                using (streamWriter = new StreamWriter(fileStream, System.Text.Encoding.UTF8))
                {

                    streamWriter.WriteLine(string.Concat(DateTime.Now.ToString(), " ", log));
                    streamWriter.Close();
                }

                fileStream.Close();
            }
        }
    }

    /// <summary>
    /// The SqlHelper class is intended to encapsulate high performance, 
    /// scalable best practices for common uses of SqlClient.
    /// </summary>
    public abstract class SqlHelper
    {

        //Database connection strings
        public static readonly string mainConnString = ConfigurationManager.ConnectionStrings["mainConnString"].ConnectionString;


        // Hashtable to store cached parameters
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        public static SqlParameter CreateInputParam(string paramName, SqlDbType dbType, object objValue)
        {

            SqlParameter param = new SqlParameter(paramName, dbType);

            if (objValue == null)
            {
                param.IsNullable = true;
                param.Value = DBNull.Value;
            }
            else
            {
                param.Value = objValue;
            }

            return param;
        }

        public static object CheckForNullString(string text)
        {
            if (text == null || text.Trim().Length == 0)
            {
                return System.DBNull.Value;
            }
            else
            {
                return text;
            }
        }

        public static SqlParameter MakeInParam(string ParamName, object Value)
        {
            return new SqlParameter(ParamName, Value);
        }

        /// <summary>
        /// Make input param.
        /// </summary>
        /// <param name="ParamName">Name of param.</param>
        /// <param name="DbType">Param type.</param>
        /// <param name="Size">Param size.</param>
        /// <param name="Value">Param value.</param>
        /// <returns>New parameter.</returns>
        public static SqlParameter MakeInParam(string ParamName, SqlDbType DbType, int Size, object Value)
        {
            return MakeParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
        }

        /// <summary>
        /// Make input param.
        /// </summary>
        /// <param name="ParamName">Name of param.</param>
        /// <param name="DbType">Param type.</param>
        /// <param name="Size">Param size.</param>
        /// <returns>New parameter.</returns>
        public static SqlParameter MakeOutParam(string ParamName, SqlDbType DbType, int Size)
        {
            return MakeParam(ParamName, DbType, Size, ParameterDirection.Output, null);
        }

        /// <summary>
        /// Make stored procedure param.
        /// </summary>
        /// <param name="ParamName">Name of param.</param>
        /// <param name="DbType">Param type.</param>
        /// <param name="Size">Param size.</param>
        /// <param name="Direction">Parm direction.</param>
        /// <param name="Value">Param value.</param>
        /// <returns>New parameter.</returns>
        public static SqlParameter MakeParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
        {
            SqlParameter param;

            if (Size > 0)
                param = new SqlParameter(ParamName, DbType, Size);
            else
                param = new SqlParameter(ParamName, DbType);

            param.Direction = Direction;
            if (!(Direction == ParameterDirection.Output && Value == null))
                param.Value = Value;

            return param;
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();

                conn.Close();
                conn.Dispose();

                return val;
            }
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            int val = 0;

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();

            connection.Close();
            connection.Dispose();

            return val;
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="trans">an existing sql transaction</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                conn.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();

                connection.Close();
                connection.Dispose();

                return val;
            }
        }

        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// add parameter array to the cache
        /// </summary>
        /// <param name="cacheKey">Key to the parameter cache</param>
        /// <param name="cmdParms">an array of SqlParamters to be cached</param>
        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// Retrieve cached parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParamters array</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey)
        {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }

        /// <summary>
        /// Prepare a command for execution
        /// </summary>
        /// <param name="cmd">SqlCommand object</param>
        /// <param name="conn">SqlConnection object</param>
        /// <param name="trans">SqlTransaction object</param>
        /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
        /// <param name="cmdText">Command text, e.g. Select * from Products</param>
        /// <param name="cmdParms">SqlParameters to use in the command</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        #region ExecuteDataSet

        /// <summary>
        /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in 
        /// the connection string. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <returns>a dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
        {
            //pass through the call providing null for the set of SqlParameters
            return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
        }

        /// <summary>
        /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>a dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            //create & open a SqlConnection, and dispose of it after we are done.
            using (SqlConnection cn = new SqlConnection(connectionString))
            {
                cn.Open();

                //call the overload that takes a connection in place of the connection string
                DataSet ds = ExecuteDataset(cn, commandType, commandText, commandParameters);

                cn.Close();
                cn.Dispose();
                return ds;
            }
        }

        /// <summary>
        /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
        /// </remarks>
        /// <param name="connection">a valid SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <returns>a dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
        {
            //pass through the call providing null for the set of SqlParameters
            return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
        }

        /// <summary>
        /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">a valid SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>a dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            //create a command and prepare it for execution
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

            //create the DataAdapter & DataSet
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            //fill the DataSet using default values for DataTable names, etc.
            da.Fill(ds);

            // detach the SqlParameters from the command object, so they can be used again.			
            cmd.Parameters.Clear();

            connection.Close();
            connection.Dispose();
            //return the dataset
            return ds;
        }


        /// <summary>
        /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
        /// </remarks>
        /// <param name="transaction">a valid SqlTransaction</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <returns>a dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
        {
            //pass through the call providing null for the set of SqlParameters
            return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
        }

        /// <summary>
        /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="transaction">a valid SqlTransaction</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>a dataset containing the resultset generated by the command</returns>
        public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            //create a command and prepare it for execution
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);

            //create the DataAdapter & DataSet
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            //fill the DataSet using default values for DataTable names, etc.
            da.Fill(ds);

            // detach the SqlParameters from the command object, so they can be used again.
            cmd.Parameters.Clear();

            //return the dataset
            return ds;
        }



        #endregion ExecuteDataSet

        #region ExecuteDataTable

        /// <summary>
        /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in 
        /// the connection string. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataTable dt = ExecuteDataTable(connString, CommandType.StoredProcedure, "GetOrders");
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <returns>a DataTable containing the resultset generated by the command</returns>
        public static DataTable ExecuteDataTable(string connectionString, CommandType commandType, string commandText)
        {
            //pass through the call providing null for the set of SqlParameters
            return ExecuteDataTable(connectionString, commandType, commandText, (SqlParameter[])null);
        }

        /// <summary>
        /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataTable dt = ExecuteDataTable(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>a DataTable containing the resultset generated by the command</returns>
        public static DataTable ExecuteDataTable(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            //create & open a SqlConnection, and dispose of it after we are done.
            using (SqlConnection cn = new SqlConnection(connectionString))
            {
                cn.Open();

                //call the overload that takes a connection in place of the connection string
                DataTable dt = ExecuteDataTable(cn, commandType, commandText, commandParameters);

                cn.Close();
                cn.Dispose();

                return dt;
            }
        }

        /// <summary>
        /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataTable dt = ExecuteDataTable(conn, CommandType.StoredProcedure, "GetOrders");
        /// </remarks>
        /// <param name="connection">a valid SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <returns>a DataTable containing the resultset generated by the command</returns>
        public static DataTable ExecuteDataTable(SqlConnection connection, CommandType commandType, string commandText)
        {
            //pass through the call providing null for the set of SqlParameters
            return ExecuteDataTable(connection, commandType, commandText, (SqlParameter[])null);
        }

        /// <summary>
        /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataTable dt = ExecuteDataTable(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">a valid SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>a DataTable containing the resultset generated by the command</returns>
        public static DataTable ExecuteDataTable(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            //create a command and prepare it for execution
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

            //create the DataAdapter & DataTable
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();

            //fill the DataTable using default values for DataTable names, etc.
            da.Fill(dt);

            // detach the SqlParameters from the command object, so they can be used again.			
            cmd.Parameters.Clear();

            connection.Close();
            connection.Dispose();

            //return the DataTable
            return dt;
        }


        /// <summary>
        /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction. 
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataTable dt = ExecuteDataTable(trans, CommandType.StoredProcedure, "GetOrders");
        /// </remarks>
        /// <param name="transaction">a valid SqlTransaction</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <returns>a DataTable containing the resultset generated by the command</returns>
        public static DataTable ExecuteDataTable(SqlTransaction transaction, CommandType commandType, string commandText)
        {
            //pass through the call providing null for the set of SqlParameters
            return ExecuteDataTable(transaction, commandType, commandText, (SqlParameter[])null);
        }

        /// <summary>
        /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataTable dt = ExecuteDataTable(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="transaction">a valid SqlTransaction</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>a DataTable containing the resultset generated by the command</returns>
        public static DataTable ExecuteDataTable(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            //create a command and prepare it for execution
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);

            //create the DataAdapter & DataTable
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();

            //fill the DataTable using default values for DataTable names, etc.
            da.Fill(dt);

            // detach the SqlParameters from the command object, so they can be used again.
            cmd.Parameters.Clear();

            //return the DataTable
            return dt;
        }

        #endregion ExecuteDataTable
    }
}